//
//  EventViewController.m
//  Ringminder
//
//  Created by Think Small Studio on 09-6-20.
//  Copyright 2009 Think Small Studio. All rights reserved.
//

#import "EventViewController.h"
#import "RingminderAppDelegate.h"
#import "NameViewController.h"
#import "TimePickerViewController.h"
#import "RepeatViewController.h"
#import "SoundAlertTimeViewController.h"


@implementation EventViewController
@synthesize eventParaTableView;
@synthesize paraNameList;
@synthesize editingItem;
@synthesize editingItemCopy;
@synthesize appHelper;


 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
		appHelper = [[AppHelper alloc] init];
    }
    return self;
}



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	NSArray *array = [[NSArray alloc] initWithObjects:@"Name", @"Begin Time", @"End Time",
					  @"Repeat", @"Sound", @"Alert Time", nil];
	self.paraNameList = array;
	[array release];
	
	// Set the left button Cancel
	self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel 
																						   target:self action:@selector(cancel:)] autorelease];
	
	// Set the right button Save
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave 
																							target:self action:@selector(save:)] autorelease];
}

// When we set the editing item, we also make a copy in case edits are made and then canceled - then we can
// restore from the copy.
- (void)setEditingItem:(NSMutableDictionary *)anItem {
    [editingItem release];
    editingItem = [anItem retain];
    self.editingItemCopy = editingItem;
}

- (IBAction)cancel:(id)sender {
	// cancel edits, restore all values from the copy
    newItem = NO;
    [editingItem setValuesForKeysWithDictionary:editingItemCopy];
	[self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)save:(id)sender {
	// First check if the end time is later than the begin time
	NSDate *begintime = [editingItem valueForKey:@"begintime"];
	NSDate *endtime = [editingItem valueForKey:@"endtime"];
	NSComparisonResult comparisonResult = [begintime compare:endtime];
	if (comparisonResult != NSOrderedAscending) {
		
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Notice"
														message:@"End time should be later than begin time." 
													   delegate:[[UIApplication sharedApplication] delegate] cancelButtonTitle:@"OK" otherButtonTitles:nil];
		
		[alert show];
		[alert release];
		return;
	}
	
	// If this is to create a new event
    if (newItem) {
		RingminderAppDelegate *appDelegate = (RingminderAppDelegate *)[[UIApplication sharedApplication] delegate];
		[appDelegate.appData addObject:editingItem];
        newItem = NO;
    }
	
	// Pop the view to return to the main event list
	[self.navigationController popViewControllerAnimated:YES];
}

// Call this function whenever the view will appear
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	
	// If this is to add a new event
	if (editingItem == nil) {
		self.title = @"Add Event";
		NSString *name = [NSString string];
		name = @"New Event";
		NSDate *begintime = [NSDate date];
		NSDate *endtime = [NSDate dateWithTimeIntervalSinceNow:3600.0];
		NSMutableArray *repeat = [NSMutableArray arrayWithCapacity:0];
		NSUInteger i;
		for (i = 0; i < 7; i ++) {
			[repeat addObject:[NSNumber numberWithBool:NO]];
		}
		NSNumber *sound = [NSNumber numberWithInt:0];
		NSNumber *alerttime =  [NSNumber numberWithInt:0];
		
		self.editingItem = [NSMutableDictionary dictionaryWithObjectsAndKeys:name, @"name", begintime, @"begintime", endtime, @"endtime", repeat, @"repeat", sound, @"sound", alerttime, @"alerttime", nil];
		
		newItem = YES;
	}
	// If to modify an existing event
	else {
		self.title = @"Modify Event";
	}
	
	// Refesh the content of the table to reflect the changes
	[eventParaTableView reloadData];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [self.paraNameList count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
    }
    
	// Configure the cell.
	cell.textLabel.text = [paraNameList objectAtIndex:indexPath.row];
	switch (indexPath.row) {
		case 0:
			cell.detailTextLabel.text = [editingItem valueForKey:@"name"];
			break;
		case 1:
			cell.detailTextLabel.text = [appHelper getTimeString:[editingItem valueForKey:@"begintime"]];
			break;
		case 2:
			cell.detailTextLabel.text = [appHelper getTimeString:[editingItem valueForKey:@"endtime"]];
			break;
		case 3:
			cell.detailTextLabel.text = [appHelper getRepeatString:[editingItem objectForKey:@"repeat"]];
			break;
		case 4:
			cell.detailTextLabel.text = [appHelper getSoundString:[[editingItem valueForKey:@"sound"] intValue]];
			break;
		case 5:
			cell.detailTextLabel.text = [appHelper getAlertTimeString:[[editingItem valueForKey:@"alerttime"] intValue]];
			break;
		default:
			break;
	}

	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	
    return cell;
}

// Override to support row selection in the table view.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
    // Navigation logic may go here -- for example, create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController animated:YES];
	// [anotherViewController release];
	[eventParaTableView deselectRowAtIndexPath:indexPath animated:NO];
	
	if (indexPath.row == 0) {
		NameViewController *controller = [[NameViewController alloc] initWithNibName:@"NameViewController" bundle:nil];
		controller.editingItem = self.editingItem;
		[self.navigationController pushViewController:controller animated:YES];
		[controller release];
	}
	else if (indexPath.row == 1 || indexPath.row == 2) {
		TimePickerViewController *controller = [[TimePickerViewController alloc] initWithNibName:@"TimePickerViewController" bundle:nil];
		controller.editingItem = self.editingItem;
		controller.row = indexPath.row;
		[self.navigationController pushViewController:controller animated:YES];
		[controller release];		
	}
	else if (indexPath.row == 3) {
		RepeatViewController *controller = [[RepeatViewController alloc] initWithNibName:@"RepeatViewController" bundle:nil];
		controller.editingItem = self.editingItem;
		[self.navigationController pushViewController:controller animated:YES];
		[controller release];		
	}
	else if (indexPath.row == 4 || indexPath.row == 5) {
		SoundAlertTimeViewController *controller = [[SoundAlertTimeViewController alloc] initWithNibName:@"SoundAlertTimeViewController" bundle:nil];
		controller.editingItem = self.editingItem;
		controller.row = indexPath.row;
		[self.navigationController pushViewController:controller animated:YES];
		[controller release];
	}
	else {
		// will never happen here
	}
}

- (void)dealloc {
	[eventParaTableView release];
	[paraNameList release];
	[editingItem release];
	[editingItemCopy release];
	[appHelper release];
    [super dealloc];
}


@end
